#include "LabelHeap.h"
//necessary
#include "memory-tools.h"
#include "Hash-tools.h"
#include <string.h>

/*FIXME ok ora devo fare la creazione del file store. Durante la compilazione di un nuovo pacchetto le label verranno ficcate in una
 * lista. A file .kaboom finito, dalla lista verrà creato il file store.
 */

//TODO testing
PlabelHeapInfo loadLabelHeap(FILE* store){
	//start of the file store
	FILE* storeBegin;
	//memory to malloc to store the whole file in the memory heap
	int memoryToMalloc;
	//final pointer to return
	PlabelHeapInfo result;
	//address to the hashtable
	void* hashpointer;


	result=(PlabelHeapInfo)mallocMemory(sizeof(LabelHeapInfo),"LabelHeap.c:loadLabelHeap:1");

	storeBegin=store;
	//header building
	fscanf(store,"%du",&(result->n_1));
	fscanf(store,"%du",&(result->n_2));
	fscanf(store,"%du",&(result->heapsize));

	//now we malloc (data heap JUST AFTER the hashtable) both the hashtable and the heap
	memoryToMalloc=
		result->n_1*sizeof(unsigned int)+	//hashtable size
		1+							//padding (is equal to the index cell n_1 of the hashtable)
		result->heapsize;			//heap size

	hashpointer=mallocMemory(memoryToMalloc,"LabelHeap.c:loadLabelHeap:2");
	memcpy(hashpointer,storeBegin,memoryToMalloc);
	return result;
}

//TODO testing
Plabel findLabelData(Plabel labeltofind, PlabelHeapInfo heap){
	int i=0;
	MainHash j;
	DirectHash labelhash=hashString(labeltofind->name);
	//value of a cell in the hashtable
	unsigned int T_j;

	do {
		j=hash(labelhash,i,heap->n_1,heap->n_2,heap->n_1);
		T_j=heap->hashtable[j];
		if (T_j==0){//no additional hash will be found after this. The Label is not inside the heap
			return NULL;
		}
		if ((DirectHash)(heap->heap+T_j)==labelhash){//the key stored in the heap is the key itself: found!
			return (Plabel)(heap->heap+T_j+sizeof(DirectHash));
		}
		i++;
	}while(i==heap->n_1);

	return NULL;
}
